/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.hiddendanger.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.drew.imaging.ImageMetadataReader;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.Tag;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.itextpdf.text.Image;
import com.koron.common.bean.StaffBean;
import com.koron.common.dfs.FastDFSClientWrapper;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.common.web.Util;
import com.koron.hazardsource.domain.IndicationItems;
import com.koron.hazardsource.mapper.IndicationItemsMapper;
import com.koron.hiddendanger.bean.HiddenDangerRectificationNotice;
import com.koron.hiddendanger.bean.HiddenDangerRectificationReport;
import com.koron.hiddendanger.bean.NoticeItem;
import com.koron.hiddendanger.bean.ReportItem;
import com.koron.hiddendanger.domain.CheckRecord;
import com.koron.hiddendanger.domain.HiddenDangerDiscovery;
import com.koron.hiddendanger.domain.HiddenDangerRectification;
import com.koron.hiddendanger.mapper.CheckRecordMapper;
import com.koron.hiddendanger.mapper.HiddenDangerMapper;
import com.koron.hiddendanger.mapper.HiddenDangerRectificationMapper;
import com.koron.hiddendanger.service.api.HiddenDangerRectificationService;
import com.koron.hiddendanger.uitls.BusinessCode;
import com.koron.risk.bean.CorpBean;
import com.koron.risk.mapper.CorpManagementMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.RegionUtil;
import org.apache.poi.xssf.usermodel.*;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import com.itextpdf.text.Font;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class HiddenDangerRectificationServiceImpl implements HiddenDangerRectificationService {

    private final static Logger logger = LoggerFactory.getLogger(HiddenDangerRectificationServiceImpl.class);

    @Autowired
    private Util util;

    @Autowired
    private FastDFSClientWrapper clientWrapper;

    private final static SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");

    /**
     * 生成隐患整改通知书
     *
     * @param factory
     * @param user
     * @param discoveryList
     */
    public static String generateHiddenDangerRectificationNotice(SessionFactory factory, StaffBean user, List<HiddenDangerDiscovery> discoveryList) {
        try {
            HiddenDangerRectificationMapper mapper = factory.getMapper(HiddenDangerRectificationMapper.class);
            if (null != discoveryList && discoveryList.size() > 0) {
                // 获取编号
                String noticeCode = generateNoteceCode(factory);
                List<NoticeItem> itemList = new ArrayList<>();
                HiddenDangerRectificationNotice notice = new HiddenDangerRectificationNotice();
                notice.setId(DefaultIdGenerator.getInstance().generateLongId());
                notice.setAddTime(new Date());
                notice.setAddUser(user.getCode());
                notice.setAddUserName(user.getName());
                notice.setUpdateTime(new Date());
                notice.setUpdateUser(user.getCode());
                notice.setUpdateUserName(user.getName());
                notice.setNoticeCode(noticeCode);
                notice.setNoticeTime(new Date());
                notice.setCorpCode(discoveryList.get(0).getCorpCode());
                notice.setCheckUnit(discoveryList.get(0).getCheckUnit());
                notice.setCheckUnitName(discoveryList.get(0).getCheckUnitName());
                List<String> unit = new ArrayList<>();
                List<String> unitName = new ArrayList<>();
                Set<String> inspectors = new LinkedHashSet<>();
                Set<String> inspectorsName = new LinkedHashSet<>();
                Date date = new Date();
                for (HiddenDangerDiscovery dangerDiscovery : discoveryList) {
                    if (StringUtils.isNotEmpty(dangerDiscovery.getCheckRecordId())) {
                        CheckRecord record = factory.getMapper(CheckRecordMapper.class).queryOne(dangerDiscovery.getCheckRecordId());
                        if (null != record) {
                            if (StringUtils.isNotEmpty(record.getDescription())) {
                                notice.setCheckNote(record.getDescription());
                            }
                        }
                    }
                    if (!unit.contains(dangerDiscovery.getGridCode())) {
                        unit.add(dangerDiscovery.getGridCode());
                    }
                    if (!unitName.contains(dangerDiscovery.getGridName())) {
                        unitName.add(dangerDiscovery.getGridName());
                    }
                    if (StringUtils.isNotEmpty(dangerDiscovery.getDiscovererCode())) {
                        Set<String> collect = JSONArray.parseArray(dangerDiscovery.getDiscovererCode(), String.class).stream().collect(Collectors.toSet());
                        inspectors.addAll(collect);
                    }
                    if (StringUtils.isNotEmpty(dangerDiscovery.getDiscovererDepartment())) {
                        Set<String> collect = JSONArray.parseArray(dangerDiscovery.getDiscovererDepartment(), String.class).stream().collect(Collectors.toSet());
                        inspectorsName.addAll(collect);
                    }
                    NoticeItem item = new NoticeItem();
                    item.setHiddenDangerId(dangerDiscovery.getId());
                    item.setCheckDate(dangerDiscovery.getDiscoveryTime());
                    item.setDescription(dangerDiscovery.getDescription());
                    item.setHandlingOpinions(dangerDiscovery.getHandlingOpinions());
                    if (null != dangerDiscovery.getRectificationPeriod()) {
                        Date rectificationPeriod = dangerDiscovery.getRectificationPeriod();
                        if (date.before(rectificationPeriod)) {
                            date = rectificationPeriod;
                        }
                        item.setRectificationPeriod(sdf.format(rectificationPeriod));
                    }
                    if (StringUtils.isNotEmpty(dangerDiscovery.getLocation())) {
                        item.setCheckLocation(dangerDiscovery.getLocation());
                    }
                    if (StringUtils.isNotEmpty(dangerDiscovery.getAttachment())) {
                        item.setHiddenDangerAttachment(dangerDiscovery.getAttachment());
                    }
                    item.setNoticeId(notice.getId());
                    itemList.add(item);
                }
                notice.setRectificationPeriod(sdf.format(date));
                notice.setInspectedUnit(unit.stream().collect(Collectors.joining(",")));
                notice.setInspectedUnitName(unitName.stream().collect(Collectors.joining(",")));
                notice.setInspectors(inspectors.stream().collect(Collectors.joining(",")));
                notice.setInspectorsName(inspectorsName.stream().collect(Collectors.joining(",")));
                mapper.insertNotice(notice);
                mapper.insertNoticeItem(itemList);
                // 将隐患整改通知书编号关联到隐患中
                List<String> idList = discoveryList.stream().map(bean -> bean.getId()).collect(Collectors.toList());
                mapper.updateDangerNoticeCode(noticeCode, idList);
                return noticeCode;
            }
            return null;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            return null;
        }
    }


    public static String generateNoteceCode(SessionFactory factory) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        StringBuilder sb = new StringBuilder();
        // 获取当前日期
        String date = sdf.format(new Date());
        StringBuilder builder = sb.append(date);
        // 根据当前时间查询已存在的最大code
        String maxCode = factory.getMapper(HiddenDangerRectificationMapper.class).queryMaxCode(builder.toString());
        if (null == maxCode) {
            builder.append("001");
            return builder.toString();
        }
        // 截取最后三位
        String substring = maxCode.substring(maxCode.length() - 3);
        //末位加1
        long lastNum = Long.parseLong("1" + substring) + 1;
        // 替换最后三位
        maxCode = maxCode.substring(0, maxCode.length() - 3) + (lastNum + "").substring(1);
        return maxCode;
    }


    @Override
    public MessageBean<DataBean<HiddenDangerRectificationNotice>> getNoticeList(StaffBean user, String corpCode, String checkUnit, String inspectedUnitName, Integer start, Integer pageSize,String keyword,String noticeCode) {
        SessionFactory factory = null;
        MessageBean<DataBean<HiddenDangerRectificationNotice>> msg = new MessageBean<>();
        try {
            factory = new SessionFactory();
            String codes = util.getCodes(corpCode);
            List<HiddenDangerRectificationNotice> list = factory.getMapper(HiddenDangerRectificationMapper.class).getNoticeList(codes, corpCode, checkUnit, inspectedUnitName, start, pageSize,keyword,noticeCode);
            Integer count = factory.getMapper(HiddenDangerRectificationMapper.class).getNoticeCount(codes, corpCode, checkUnit, inspectedUnitName,keyword,noticeCode);
            pageSize = null == pageSize ? count : (pageSize <= 0 ? 1 : pageSize);
            Integer totalPage = count > pageSize ? count % pageSize == 0 ? count / pageSize : count / pageSize + 1 : 1;
            DataBean<HiddenDangerRectificationNotice> dataBean = new DataBean<>();
            dataBean.setPageSize(pageSize);
            if (null != list && list.size() > 0) {
                for (HiddenDangerRectificationNotice notice : list) {
                    if (StringUtils.isNotEmpty(notice.getCorpCode())) {
                        CorpBean corpBean = factory.getMapper(CorpManagementMapper.class).get(notice.getCorpCode());
                        notice.setCorpName(corpBean == null ? null : corpBean.getCorpName());
                    }
                    if (("776B361BFFAC4F00BBF459CD1303A8B2").equals(notice.getCheckUnit())) {
                        notice.setCheckUnitName(notice.getCheckUnitName() + "安委办");
                    }
                    List<NoticeItem> noticeItem = factory.getMapper(HiddenDangerRectificationMapper.class).getNoticeItem(notice.getId());
                    notice.setNoticeList(noticeItem);
                }
            }
            dataBean.setList(list);
            dataBean.setTotalPage(totalPage);
            dataBean.setTotalNumber(count);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setData(dataBean);
            msg.setDescription("获取隐患整改通知书列表成功");
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }

    @Override
    public MessageBean<HiddenDangerRectificationNotice> getNotice(String id) {
        MessageBean<HiddenDangerRectificationNotice> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(id)) {
                msg.setCode(BusinessCode.CHECKRECORD_EMPTY_CHANGE_DATA.getCode());
                msg.setDescription(BusinessCode.CHECKRECORD_EMPTY_CHANGE_DATA.getDescription());
                return msg;
            }
            HiddenDangerRectificationNotice notice = factory.getMapper(HiddenDangerRectificationMapper.class).getNotice(id);
            if (null != notice) {
                if (StringUtils.isNotEmpty(notice.getCorpCode())) {
                    CorpBean corpBean = factory.getMapper(CorpManagementMapper.class).get(notice.getCorpCode());
                    notice.setCorpName(corpBean == null ? null : corpBean.getCorpName());
                }
                List<NoticeItem> noticeItem = factory.getMapper(HiddenDangerRectificationMapper.class).getNoticeItem(notice.getId());
                notice.setNoticeList(noticeItem);
            }
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("查询整改通知书详情成功");
            msg.setData(notice);
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    /**
     * 删掉对应的隐患整改通知书信息
     *
     * @param factory
     * @param idLists
     */
    public static void DeleteNotice(SessionFactory factory, List<String> idLists) {
        // 根据隐患id获取隐患整改通知书id
        List<String> noticeIds = factory.getMapper(HiddenDangerRectificationMapper.class).getNoticeId(idLists);
        factory.getMapper(HiddenDangerRectificationMapper.class).batchDeleteNoticeItem(idLists);
        if (null != noticeIds && noticeIds.size() > 0) {
            factory.getMapper(HiddenDangerRectificationMapper.class).batchDeleteNotice(noticeIds);
        }
    }


    /**
     * 隐患审批通过后，生成隐患整改报告
     *
     * @param factory
     * @param idLists
     * @throws Exception
     */
    public static void generateHiddenDangerRectificationReport(SessionFactory factory, List<String> idLists) {
        try {
            if (null != idLists && idLists.size() > 0) {
                List<HiddenDangerRectificationReport> reportList = new ArrayList<>();
                // 获取所有的隐患整改通知
                HiddenDangerMapper dangerMapper = factory.getMapper(HiddenDangerMapper.class);
                HiddenDangerRectificationMapper mapper = factory.getMapper(HiddenDangerRectificationMapper.class);
                // 根据隐患id获取隐患整改通知id
                List<String> noticeIds = mapper.getNoticeId(idLists);
                // 获取所有的隐患整改通知
                if (null != noticeIds && noticeIds.size() > 0) {
                    List<HiddenDangerRectificationNotice> noticeList = mapper.getNoticeListByIds(noticeIds);
                    // 根据隐患整改通知，生成对应的整改报告。一个整改通知，对应一个整改报告
                    if (null != noticeList && noticeList.size() > 0) {
                        for (HiddenDangerRectificationNotice notice : noticeList) {
                            HiddenDangerRectificationReport report = new HiddenDangerRectificationReport();
                            report.setId(DefaultIdGenerator.getInstance().generateLongId());
                            report.setAddTime(new Date());
                            report.setUpdateTime(new Date());
                            report.setCorpCode(notice.getCorpCode());
                            report.setNoticeId(notice.getId());
                            report.setNoticeCode(notice.getNoticeCode());
                            report.setReportName(notice.getNoticeCode() + "安全隐患整改报告");
                            report.setCheckUnit(notice.getCheckUnit());
                            report.setCheckUnitName(notice.getCheckUnitName());
                            report.setNoticeTime(notice.getNoticeTime());
                            report.setReportTime(new Date());
                            reportList.add(report);
                        }
                    }
                }
                if (null != reportList && reportList.size() > 0) {
                    for (HiddenDangerRectificationReport report : reportList) {
                        List<ReportItem> reportItemList = new ArrayList<>();
                        // 获取整改通知书对应的隐患id
                        List<String> discoveryIds = mapper.getHiddenDangerDiscoveryId(report.getNoticeId());
                        // 获取对应的隐患信息及整改信息
                        List<HiddenDangerDiscovery> dangerDiscoveryList = dangerMapper.queryDangerByIdList(discoveryIds);
                        if (null != dangerDiscoveryList && dangerDiscoveryList.size() > 0) {
                            for (HiddenDangerDiscovery discovery : dangerDiscoveryList) {
                                ReportItem reportItem = new ReportItem();
                                reportItem.setReportId(report.getId());
                                reportItem.setHiddenDangerId(discovery.getId());
                                // 获取问题描述
                                if (StringUtils.isNotEmpty(discovery.getDescription())) {
                                    reportItem.setDescription(discovery.getDescription());
                                }
                                // 获取整改前照片
                                if (StringUtils.isNotEmpty(discovery.getAttachment())) {
                                    reportItem.setPhotosBeforeRectification(discovery.getAttachment());
                                }
                                // 获取隐患整改情况信息
                                List<HiddenDangerRectification> hiddenDangerRectifications = dangerMapper.queryRectificationByDangerRecordId(discovery.getId());
                                if (null != hiddenDangerRectifications && hiddenDangerRectifications.size() > 0) {
                                    HiddenDangerRectification rectification = hiddenDangerRectifications.get(0);
                                    IndicationItems itemsFinished = factory.getMapper(IndicationItemsMapper.class).matchIndicationItems("隐患整改状态", "已整改");
                                    rectification.setRectificationState(itemsFinished == null ? null : itemsFinished.getId());
                                    factory.getMapper(HiddenDangerMapper.class).updateRectification(rectification);
                                        // 获取整改措施
//                                    reportItem.setCorrectiveMeasures(rectification.getSolution());
                                    // 获取整改结果
                                    reportItem.setCorrectiveResult(rectification.getRectificationResult());
                                    // 获取隐患整改期限
                                    reportItem.setPlanTime(rectification.getDeadline());
                                    // 获取整改完成时间
                                    reportItem.setFinishTime(rectification.getCompleteTime());
                                    //获取整改后照片
                                    if (StringUtils.isNotEmpty(rectification.getRectificationAttachment())) {
                                        reportItem.setPhotosAfterRectification(rectification.getRectificationAttachment());
                                    }
                                }
                                reportItemList.add(reportItem);
                            }
                        }
                        // 添加整改报告
                        mapper.insertReport(report);
                        mapper.batchInsertReportItem(reportItemList);
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
        }
    }


    @Override
    public MessageBean<HiddenDangerRectificationReport> getReport(String id) {
        MessageBean<HiddenDangerRectificationReport> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(id)) {
                msg.setCode(BusinessCode.CHECKRECORD_EMPTY_CHANGE_DATA.getCode());
                msg.setDescription(BusinessCode.CHECKRECORD_EMPTY_CHANGE_DATA.getDescription());
                return msg;
            }
            HiddenDangerRectificationReport report = factory.getMapper(HiddenDangerRectificationMapper.class).getReport(id);
            if (null != report) {
                if (StringUtils.isNotEmpty(report.getCorpCode())) {
                    CorpBean corpBean = factory.getMapper(CorpManagementMapper.class).get(report.getCorpCode());
                    report.setCorpName(corpBean == null ? null : corpBean.getCorpName());
                }
                List<ReportItem> reportItem = factory.getMapper(HiddenDangerRectificationMapper.class).getReportItem(report.getId());
                report.setReportItemList(reportItem);
            }
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("查询整改报告详情成功");
            msg.setData(report);
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<?> fileImport(Integer type, String reportId, String hiddenDangerId, MultipartFile[] files) {
        SessionFactory factory = null;
        MessageBean<String> msg = new MessageBean<>();
        List<String> fileUrlList = new ArrayList<>();
        try {
            factory = new SessionFactory();
            // 获取整改报告详情信息
            ReportItem reportItem = factory.getMapper(HiddenDangerRectificationMapper.class).getReportItemOne(reportId, hiddenDangerId);
            if (null == reportItem) {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("整改报告不存在");
                factory.close();
                return msg;
            }
            List<String> keepAtts = null;
            if (null != files && files.length > 0) {
                if (type == 1) {
                    keepAtts = JSONArray.parseArray(reportItem.getPhotosBeforeRectification(), String.class);
                } else if (type == 2) {
                    keepAtts = JSONArray.parseArray(reportItem.getPhotosAfterRectification(), String.class);
                }
                if (null == keepAtts) {
                    keepAtts = new ArrayList<>();
                }
                for (MultipartFile file : files) {
                    String fileName = file.getOriginalFilename();
                    //获取文件后缀名
                    String substring = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                    //判断是否属于图片
                    boolean contains = Lists.newArrayList("bmp", "gif", "jpg", "psd", "tiff", "eps", "tga", "jpeg", "png").contains(substring);
                    if (!contains) {
                        factory.close();
                        msg.setCode(BusinessCode.FAILURE.getCode());
                        msg.setDescription(fileName + "不是图片，请上传图片");
                        return msg;
                    }
                    String url = clientWrapper.uploadFile(file);
                    keepAtts.add(url + "#" + file.getOriginalFilename());
                    fileUrlList.add(url + "#" + file.getOriginalFilename());
                }
                if (null != keepAtts && keepAtts.size() > 0) {
                    if (type == 1) {
                        reportItem.setPhotosBeforeRectification(new Gson().toJson(keepAtts));
                    } else if (type == 2) {
                        reportItem.setPhotosAfterRectification(new Gson().toJson(keepAtts));
                    }
                }
                Integer value = factory.getMapper(HiddenDangerRectificationMapper.class).updateReportItem(reportItem);
                if (value > 0) {
                    msg.setData(fileUrlList.stream().collect(Collectors.joining(",")));
                }
            }
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("上传成功");
            factory.close();
            return msg;
        } catch (Exception e) {
            if (null != factory) {
                factory.close(false);
            }
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("上次失败");
            return msg;
        }
    }

    @Override
    public MessageBean<?> deleteFile(Integer type, String reportId, String hiddenDangerId, String fileUrl) {
        SessionFactory factory = null;
        MessageBean<Integer> msg = new MessageBean<>();
        try {
            factory = new SessionFactory();
            // 获取整改报告详情信息
            ReportItem reportItem = factory.getMapper(HiddenDangerRectificationMapper.class).getReportItemOne(reportId, hiddenDangerId);
            if (null == reportItem) {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("整改报告不存在");
                factory.close();
                return msg;
            }
            List<String> keepAtts = new ArrayList<>();
            if (type == 1) {
                keepAtts = JSONArray.parseArray(reportItem.getPhotosBeforeRectification(), String.class);
            } else if (type == 2) {
                keepAtts = JSONArray.parseArray(reportItem.getPhotosAfterRectification(), String.class);
            }
            if (null != keepAtts && keepAtts.contains(fileUrl)) {
                keepAtts.remove(fileUrl);
            }
            if (null != keepAtts && keepAtts.size() > 0) {
                if (type == 1) {
                    reportItem.setPhotosBeforeRectification(new Gson().toJson(keepAtts));
                } else if (type == 2) {
                    reportItem.setPhotosAfterRectification(new Gson().toJson(keepAtts));
                }
            }
            Integer value = factory.getMapper(HiddenDangerRectificationMapper.class).updateReportItem(reportItem);
            msg.setData(value);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("删除成功");
            factory.close();
            return msg;
        } catch (Exception e) {
            if (null != factory) {
                factory.close(false);
            }
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("删除失败");
            return msg;
        }
    }

    @Override
    public MessageBean<DataBean<HiddenDangerRectificationReport>> getReportList(StaffBean user, String corpCode, String checkUnit, Integer start, Integer pageSize,String reportName,String keyword) {
        SessionFactory factory = null;
        MessageBean<DataBean<HiddenDangerRectificationReport>> msg = new MessageBean<>();
        try {
            factory = new SessionFactory();
            String codes = util.getCodes(corpCode);
            List<HiddenDangerRectificationReport> list = factory.getMapper(HiddenDangerRectificationMapper.class).getReportList(codes, corpCode, checkUnit, start, pageSize,reportName,keyword);
            Integer count = factory.getMapper(HiddenDangerRectificationMapper.class).getReportCount(codes, corpCode, checkUnit,reportName,keyword);
            pageSize = null == pageSize ? count : (pageSize <= 0 ? 1 : pageSize);
            Integer totalPage = count > pageSize ? count % pageSize == 0 ? count / pageSize : count / pageSize + 1 : 1;
            DataBean<HiddenDangerRectificationReport> dataBean = new DataBean<>();
            dataBean.setPageSize(pageSize);
            if (null != list && list.size() > 0) {
                for (HiddenDangerRectificationReport report : list) {
                    if (StringUtils.isNotEmpty(report.getCorpCode())) {
                        CorpBean corpBean = factory.getMapper(CorpManagementMapper.class).get(report.getCorpCode());
                        report.setCorpName(corpBean == null ? null : corpBean.getCorpName());
                    }
                    List<ReportItem> reportItem = factory.getMapper(HiddenDangerRectificationMapper.class).getReportItem(report.getId());
                    report.setReportItemList(reportItem);
                }
            }
            dataBean.setList(list);
            dataBean.setTotalPage(totalPage);
            dataBean.setTotalNumber(count);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setData(dataBean);
            msg.setDescription("获取隐患整改报告列表成功");
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }


    /**
     * 获取所有隐患图片
     *
     * @param id
     * @param inputStream
     * @return
     */
    @Override
    public XSSFWorkbook exportNoticeByExcel(String id, InputStream inputStream) {
        // 获取整改通知书数据
        MessageBean<HiddenDangerRectificationNotice> msg = getNotice(id);
        HiddenDangerRectificationNotice notice = null;
        if (msg.getCode() == BusinessCode.SUCCESS.getCode()) {
            if (null != msg.getData()) {
                notice = msg.getData();
            }
        }
        return getNoticeWithAllPicture(notice, inputStream);
    }


    @Override
    public void exportNoticeByPdf(String id, OutputStream os) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        try {
            // 获取整改通知书数据
            MessageBean<HiddenDangerRectificationNotice> msg = getNotice(id);
            HiddenDangerRectificationNotice notice = null;
            if (msg.getCode() == BusinessCode.SUCCESS.getCode()) {
                if (null != msg.getData()) {
                    notice = msg.getData();
                }
            }
            if (null == notice) {
                return;
            } else {
                if (("776B361BFFAC4F00BBF459CD1303A8B2").equals(notice.getCheckUnit())) {
                    notice.setCheckUnitName(notice.getCheckUnitName() + "安委办");
                }
            }
            // 创建Document
            Document document = new Document();
            PdfWriter writer = PdfWriter.getInstance(document, os);
            writer.setViewerPreferences(PdfWriter.PageModeUseThumbs);
            // 设置页面大小
            document.setPageSize(PageSize.A4);
            document.open();
            // 创建一个PDF表单
            PdfPTable table = createTable(6);
            // 设置字体
            // 标题
            Font headFont = getFont(14, Font.NORMAL);
            // 内容
            Font textFont = getFont(10, Font.NORMAL);
            PdfPCell cell = new PdfPCell();
            // 设置垂直对齐方式，默认居中
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            // 设置水平对齐方式
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setPhrase(new Paragraph("安全隐患整改通知书", headFont));
            cell.setPadding(0);
            cell.setBorder(0);
            cell.setPaddingTop(0);
            cell.setPaddingBottom(10);
            cell.setColspan(6);
            table.addCell(cell);
            table.addCell(createCell(notice.getCorpName() + ":", textFont, Element.ALIGN_LEFT, 6, 0));
            StringBuffer sb = new StringBuffer();
            sb.append("此次检查存在有").append(null == notice.getNoticeList() ? 0 : notice.getNoticeList().size()).append("项安全隐患问题，请相关责任人严格按要求落实整改，于")
                    .append(notice.getRectificationPeriod()).append("完成整改并回复整改报告");
            PdfPCell cell1 = new PdfPCell();
            // 设置垂直对齐方式，默认居中
            cell1.setVerticalAlignment(Element.ALIGN_MIDDLE);
            // 设置水平对齐方式
            cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell1.setColspan(6);
            Paragraph paragraph = new Paragraph(sb.toString(), textFont);
            paragraph.setFirstLineIndent(1);
            paragraph.setIndentationLeft(20);
            cell1.addElement(paragraph);
            table.addCell(cell1);
            table.addCell(createCell("编号", textFont, Element.ALIGN_CENTER, 2, 0));
            table.addCell(createCell(notice.getNoticeCode(), textFont, Element.ALIGN_CENTER, 4, 0));
            table.addCell(createCell("被检查单位", textFont, Element.ALIGN_CENTER, 2, 0));
            table.addCell(createCell(notice.getInspectedUnitName(), textFont, Element.ALIGN_CENTER, 4, 0));
            table.addCell(createCell("检查人员", textFont, Element.ALIGN_CENTER, 2, 0));
            table.addCell(createCell(notice.getInspectorsName(), textFont, Element.ALIGN_CENTER, 4, 0));
            table.addCell(createCell("检查时间", textFont, Element.ALIGN_CENTER, 0, 0));
            table.addCell(createCell("检查存在问题", textFont, Element.ALIGN_CENTER, 0, 0));
            table.addCell(createCell("处理意见", textFont, Element.ALIGN_CENTER, 0, 0));
            table.addCell(createCell("隐患照片", textFont, Element.ALIGN_CENTER, 0, 0));
            table.addCell(createCell("隐患部位", textFont, Element.ALIGN_CENTER, 0, 0));
            table.addCell(createCell("整改时限", textFont, Element.ALIGN_CENTER, 0, 0));
            List<NoticeItem> noticeList = notice.getNoticeList();
            if (null != noticeList && noticeList.size() > 0) {
                for (NoticeItem item : noticeList) {
                    List<String> lst = new ArrayList<>();
                    String hiddenDangerAttachment = item.getHiddenDangerAttachment();
                    if (StringUtils.isNotEmpty(hiddenDangerAttachment)) {
                        lst = JSONArray.parseArray(hiddenDangerAttachment, String.class);
                    }
                    int num = lst.size() > 1 ? lst.size() : 0;
                    table.addCell(createCell(sdf.format(item.getCheckDate()), textFont, Element.ALIGN_CENTER, 0, num));
                    table.addCell(createCell(item.getDescription(), textFont, Element.ALIGN_CENTER, 0, num));
                    table.addCell(createCell(item.getHandlingOpinions(), textFont, Element.ALIGN_CENTER, 0, num));
                    if (null == lst || lst.size() == 0) {
                        table.addCell(createCell("", textFont, Element.ALIGN_CENTER, 0, 0));
                    } else {
                        String url = lst.get(0);
                        Image image = Image.getInstance(url.split("#")[0]);
                        //自定义大小
                        image.scaleAbsolute(300, 300);
                        table.addCell(new PdfPCell(image));
                        lst.remove(url);
                    }
                    table.addCell(createCell(item.getCheckLocation(), textFont, Element.ALIGN_CENTER, 0, num));
                    table.addCell(createCell(item.getRectificationPeriod(), textFont, Element.ALIGN_CENTER, 0, num));
                    if (lst.size() >= 1) {
                        for (String url : lst) {
                            Image image = Image.getInstance(url.split("#")[0]);
                            //自定义大小
                            image.scaleAbsolute(300, 300);
                            table.addCell(new PdfPCell(image));
                        }
                    }
                }
            }
            table.addCell(createCell(notice.getCheckUnitName(), textFont, Element.ALIGN_RIGHT, 6, 0));
            table.addCell(createCell(sdf.format(notice.getNoticeTime()), textFont, Element.ALIGN_RIGHT, 6, 0));
            document.add(table);
            document.close();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return;
        }

    }

    /**
     * 导出一张隐患图片
     * 默认导出第一张
     *
     * @param notice
     * @param inputStream
     * @return
     */
    public XSSFWorkbook getNoticeWithOnePicture(HiddenDangerRectificationNotice notice, InputStream inputStream) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
        XSSFWorkbook workbook = null;
        try {
            workbook = new XSSFWorkbook(inputStream);
            // 设置单元格格式
            CellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            cellStyle.setBottomBorderColor(HSSFColor.BLACK.index);
            cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            cellStyle.setLeftBorderColor(HSSFColor.BLACK.index);
            cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
            cellStyle.setRightBorderColor(HSSFColor.BLACK.index);
            cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
            cellStyle.setTopBorderColor(HSSFColor.BLACK.index);
            cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            cellStyle.setWrapText(true);
            // 设置字体
            XSSFFont font = workbook.createFont();
            font.setFontName("宋体");
            font.setFontHeightInPoints((short) 12);
            cellStyle.setFont(font);
            // 导出隐患整改通知书数据
            if (null != notice) {
                XSSFSheet sheet = workbook.getSheetAt(0);
                // 设置整改通知书内容
                XSSFRow row;
                row = sheet.getRow(1);
                row.getCell(1).setCellValue(notice.getNoticeCode());
                row.getCell(1).setCellStyle(cellStyle);
                row = sheet.getRow(2);
                row.getCell(1).setCellValue(notice.getInspectedUnitName());
                row.getCell(1).setCellStyle(cellStyle);
                row = sheet.getRow(3);
                row.getCell(1).setCellValue(notice.getInspectorsName());
                row.getCell(1).setCellStyle(cellStyle);
                int rowNum = 5;
                // 设置整改通知书明细
                List<NoticeItem> noticeList = notice.getNoticeList();
                if (null != noticeList && noticeList.size() > 0) {
                    for (NoticeItem item : noticeList) {
                        row = sheet.getRow(rowNum);
                        // 设置行高
                        row.setHeightInPoints(300);
                        String checkDate = "";
                        if (null != item.getCheckDate()) {
                            checkDate = format.format(item.getCheckDate());
                        }
                        row.createCell(0).setCellValue(checkDate);
                        row.getCell(0).setCellStyle(cellStyle);
                        row.createCell(1).setCellValue(item.getDescription());
                        row.getCell(1).setCellStyle(cellStyle);
                        row.createCell(2).setCellValue(item.getHandlingOpinions());
                        row.getCell(2).setCellStyle(cellStyle);
                        row.createCell(4).setCellValue(item.getCheckLocation());
                        row.getCell(4).setCellStyle(cellStyle);
                        row.createCell(5).setCellValue(item.getRectificationPeriod());
                        row.getCell(5).setCellStyle(cellStyle);
                        String hiddenDangerAttachment = item.getHiddenDangerAttachment();
                        XSSFDrawing drawing = sheet.createDrawingPatriarch();
                        if (StringUtils.isNotEmpty(hiddenDangerAttachment)) {
                            List<String> list = JSONArray.parseArray(hiddenDangerAttachment, String.class);
                            String url = null;
                            if (null != list && list.size() > 0) {
                                url = list.get(0).split("#")[0];
                                drawingPicture(workbook, drawing, url, 1, 1, 1, 1, 3, rowNum, 4, rowNum + 1);
                            }
                        }
                        rowNum++;
                    }
                }
                row = sheet.getRow(rowNum);
                CellStyle style = workbook.createCellStyle();
                style.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
                // 设置字体
                XSSFFont font1 = workbook.createFont();
                font1.setFontName("宋体");
                font1.setFontHeightInPoints((short) 12);
                style.setFont(font1);
                row.createCell(0).setCellValue(notice.getCorpName());
                row.getCell(0).setCellStyle(style);
                CellRangeAddress region = setRegion(rowNum, rowNum, 0, 4);
                sheet.addMergedRegion(region);
                rowNum++;
                row = sheet.getRow(rowNum);
                StringBuffer noticeTime = new StringBuffer();
                if (null != notice.getNoticeTime()) {
                    String time = format.format(notice.getNoticeTime());
                    noticeTime.append(time);
                }
                row.createCell(0).setCellValue(noticeTime.toString());
                row.getCell(0).setCellStyle(style);
                CellRangeAddress region1 = setRegion(rowNum, rowNum, 0, 5);
                sheet.addMergedRegion(region1);
            }
            return workbook;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            return null;
        }
    }

    /**
     * 导出所有隐患图片
     *
     * @param notice
     * @param inputStream
     * @return
     */
    public XSSFWorkbook getNoticeWithAllPicture(HiddenDangerRectificationNotice notice, InputStream inputStream) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
        XSSFWorkbook workbook = null;
        try {
            workbook = new XSSFWorkbook(inputStream);
            // 设置单元格格式
            CellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            cellStyle.setBottomBorderColor(HSSFColor.BLACK.index);
            cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            cellStyle.setLeftBorderColor(HSSFColor.BLACK.index);
            cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
            cellStyle.setRightBorderColor(HSSFColor.BLACK.index);
            cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
            cellStyle.setTopBorderColor(HSSFColor.BLACK.index);
            cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            cellStyle.setWrapText(true);
            // 设置字体
            XSSFFont font = workbook.createFont();
            font.setFontName("宋体");
            font.setFontHeightInPoints((short) 12);
            cellStyle.setFont(font);
            // 导出隐患整改通知书数据
            if (null != notice) {
                XSSFSheet sheet = workbook.getSheetAt(0);
                // 设置整改通知书内容
                XSSFRow row;
                row = sheet.getRow(1);
                row.getCell(1).setCellValue(notice.getNoticeCode());
                row.getCell(1).setCellStyle(cellStyle);
                row = sheet.getRow(2);
                row.getCell(1).setCellValue(notice.getInspectedUnitName());
                row.getCell(1).setCellStyle(cellStyle);
                row = sheet.getRow(3);
                row.getCell(1).setCellValue(notice.getInspectorsName());
                row.getCell(1).setCellStyle(cellStyle);
                int rowNum = 5;
                // 设置整改通知书明细
                List<NoticeItem> noticeList = notice.getNoticeList();
                if (null != noticeList && noticeList.size() > 0) {
                    for (NoticeItem item : noticeList) {
                        row = sheet.getRow(rowNum);
                        // 设置行高
                        row.setHeightInPoints(300);
                        String checkDate = "";
                        if (null != item.getCheckDate()) {
                            checkDate = format.format(item.getCheckDate());
                        }
                        row.createCell(0).setCellValue(checkDate);
                        row.getCell(0).setCellStyle(cellStyle);
                        row.createCell(1).setCellValue(item.getDescription());
                        row.getCell(1).setCellStyle(cellStyle);
                        row.createCell(2).setCellValue(item.getHandlingOpinions());
                        row.getCell(2).setCellStyle(cellStyle);
                        row.createCell(4).setCellValue(item.getCheckLocation());
                        row.getCell(4).setCellStyle(cellStyle);
                        row.createCell(5).setCellValue(item.getRectificationPeriod());
                        row.getCell(5).setCellStyle(cellStyle);
                        String hiddenDangerAttachment = item.getHiddenDangerAttachment();
                        XSSFDrawing drawing = sheet.createDrawingPatriarch();
                        int start = rowNum;
                        int end = rowNum;
                        if (StringUtils.isNotEmpty(hiddenDangerAttachment)) {
                            List<String> list = JSONArray.parseArray(hiddenDangerAttachment, String.class);
                            String url = null;
                            if (null != list && list.size() > 0) {
                                for (String urlStr : list) {
                                    row = sheet.getRow(rowNum);
                                    row.setHeightInPoints(300);
                                    url = urlStr.split("#")[0];
                                    drawingPicture(workbook, drawing, url, 1, 1, 1, 1, 3, rowNum, 4, rowNum + 1);
                                    rowNum++;
                                }
                                end = rowNum - 1;
                            }
                        } else {
                            rowNum++;
                        }
                        if (start < end) {
                            sheet.addMergedRegion(setRegion(start, end, 0, 0));
                            sheet.addMergedRegion(setRegion(start, end, 1, 1));
                            sheet.addMergedRegion(setRegion(start, end, 2, 2));
                            sheet.addMergedRegion(setRegion(start, end, 4, 4));
                            sheet.addMergedRegion(setRegion(start, end, 5, 5));
                        }
                    }
                }
                row = sheet.getRow(rowNum);
                CellStyle style = workbook.createCellStyle();
                style.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
                // 设置字体
                XSSFFont font1 = workbook.createFont();
                font1.setFontName("宋体");
                font1.setFontHeightInPoints((short) 12);
                style.setFont(font1);
                row.createCell(0).setCellValue(notice.getCorpName());
                row.getCell(0).setCellStyle(style);
                CellRangeAddress region = setRegion(rowNum, rowNum, 0, 5);
                sheet.addMergedRegion(region);
                rowNum++;
                row = sheet.getRow(rowNum);
                StringBuffer noticeTime = new StringBuffer();
                if (null != notice.getNoticeTime()) {
                    String time = format.format(notice.getNoticeTime());
                    noticeTime.append(time);
                }
                row.createCell(0).setCellValue(noticeTime.toString());
                row.getCell(0).setCellStyle(style);
                CellRangeAddress region1 = setRegion(rowNum, rowNum, 0, 5);
                sheet.addMergedRegion(region1);
            }
            return workbook;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            return null;
        }

    }

    /**
     * 向excel中插入图片
     *
     * @param workbook
     * @param drawing
     * @param url      图片路径
     * @param dx1      第1个单元格中x轴的偏移量
     * @param dy1      第1个单元格中y轴的偏移量
     * @param dx2      第2个单元格中x轴的偏移量
     * @param dy2      第2个单元格中y轴的偏移量
     * @param col1     第1个单元格的列号
     * @param row1     第1个单元格的行号
     * @param col2     第2个单元格的列号
     * @param row2     第2个单元格的行号
     */
    public void drawingPicture(XSSFWorkbook workbook, XSSFDrawing drawing, String url, int dx1, int dy1, int dx2, int dy2, int col1, int row1, int col2, int row2) {
        try {
            if (null != url) {
                File file = getFile(url);
                // 获取图片的旋转角度
                int angle = getAngle(file);
                URL imgUrl = new URL(url);
                String suffix = url.substring(url.lastIndexOf(".") + 1);
                ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
                BufferedImage bufferImg = ImageIO.read(imgUrl);
                if (angle == 90 || angle == 270) {
                    // 宽高互换
                    // 原始宽度
                    int imgWidth = bufferImg.getHeight();
                    // 原始高度
                    int imgHeight = bufferImg.getWidth();
                    // 中心点位置
                    double centerWidth = ((double) imgWidth) / 2;
                    double centerHeight = ((double) imgHeight) / 2;
                    // 图片缓存
                    BufferedImage targetImg = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);
                    // 旋转对应角度
                    Graphics2D g = targetImg.createGraphics();
                    g.rotate(Math.toRadians(angle), centerWidth, centerHeight);
                    g.drawImage(bufferImg, (imgWidth - bufferImg.getWidth()) / 2, (imgHeight - bufferImg.getHeight()) / 2, null);
                    g.rotate(Math.toRadians(-angle), centerWidth, centerHeight);
                    g.dispose();
                    ImageIO.write(targetImg, suffix, byteArrayOut);
                } else {
                    ImageIO.write(bufferImg, suffix, byteArrayOut);
                }
                XSSFClientAnchor anchor = new XSSFClientAnchor(dx1, dy1, dx2, dy2, col1, row1, col2, row2);
                //插入图片
                drawing.createPicture(anchor, workbook.addPicture(byteArrayOut.toByteArray(), XSSFWorkbook.PICTURE_TYPE_JPEG));
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
    }


    @Override
    public XSSFWorkbook exportReportByExcel(String id, InputStream inputStream) {
        // 获取整改报告数据
        MessageBean<HiddenDangerRectificationReport> msg = getReport(id);
        HiddenDangerRectificationReport report = null;
        if (msg.getCode() == BusinessCode.SUCCESS.getCode()) {
            if (null != msg.getData()) {
                report = msg.getData();
            }
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
        XSSFWorkbook workbook = null;
        try {
            workbook = new XSSFWorkbook(inputStream);
            // 导出隐患整改报告数据
            if (null != report) {
                CellStyle cellStyle = workbook.createCellStyle();
                CellStyle styleTop = workbook.createCellStyle();
                styleTop.setVerticalAlignment(VerticalAlignment.CENTER);
                styleTop.setAlignment(HSSFCellStyle.ALIGN_CENTER);
                styleTop.setWrapText(true);
//                cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
                cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
                cellStyle.setBottomBorderColor(HSSFColor.BLACK.index);
                cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
                cellStyle.setLeftBorderColor(HSSFColor.BLACK.index);
                cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
                cellStyle.setRightBorderColor(HSSFColor.BLACK.index);
                cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
                cellStyle.setTopBorderColor(HSSFColor.BLACK.index);
//                cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
                cellStyle.setWrapText(true);
                // 设置字体
                XSSFFont fontTop = workbook.createFont();
                fontTop.setFontName("宋体");
                fontTop.setFontHeightInPoints((short) 16);
                XSSFFont font = workbook.createFont();
                font.setFontName("宋体");
                font.setFontHeightInPoints((short) 12);
                cellStyle.setFont(font);
                styleTop.setFont(fontTop);
                XSSFSheet sheet = workbook.getSheetAt(0);
                // 设置整改通知书内容
                XSSFRow row;
                row = sheet.getRow(0);
                row.getCell(0).setCellValue(report.getReportName());
                row.getCell(0).setCellStyle(styleTop);
                row = sheet.getRow(2);
                row.getCell(1).setCellValue(report.getNoticeCode());
                row.getCell(1).setCellStyle(cellStyle);
                int rowNum = 3;
                // 设置整改报告明细
                List<ReportItem> reportItemList = report.getReportItemList();
                if (null != reportItemList && reportItemList.size() > 0) {
                    int index = 1;
                    for (ReportItem item : reportItemList) {
                        row = sheet.getRow(rowNum);
                        row.createCell(0).setCellValue("问题" + index + "描述:" + item.getDescription());
                        row.getCell(0).setCellStyle(cellStyle);
                        // 合并单元格并增加边框线
                        mergedRegion(1, setRegion(rowNum, rowNum, 0, 3), sheet, workbook);
                        rowNum++;
                        row = sheet.getRow(rowNum);
                        row.createCell(0).setCellValue("整改结果：" + item.getCorrectiveMeasures());
                        row.getCell(0).setCellStyle(cellStyle);
                        mergedRegion(1, setRegion(rowNum, rowNum, 0, 3), sheet, workbook);
                        rowNum++;
                        row = sheet.getRow(rowNum);
                        String planTime = "";
                        String finishTime = "";
                        if (null != item.getPlanTime()) {
                            planTime = format.format(item.getPlanTime());
                        }
                        if (null != item.getFinishTime()) {
                            finishTime = format.format(item.getFinishTime());
                        }
                        row.createCell(0).setCellValue("计划时间：" + planTime);
                        row.getCell(0).setCellStyle(cellStyle);
                        mergedRegion(1, setRegion(rowNum, rowNum, 0, 1), sheet, workbook);
                        row.createCell(2).setCellValue("完成整改时间：" + finishTime);
                        row.getCell(2).setCellStyle(cellStyle);
                        mergedRegion(1, setRegion(rowNum, rowNum, 2, 3), sheet, workbook);
                        rowNum++;
                        row = sheet.getRow(rowNum);
                        row.createCell(0).setCellValue("整改前照片");
                        row.getCell(0).setCellStyle(cellStyle);
                        mergedRegion(1, setRegion(rowNum, rowNum, 0, 1), sheet, workbook);
                        row.createCell(2).setCellValue("整改后照片");
                        row.getCell(2).setCellStyle(cellStyle);
                        mergedRegion(1, setRegion(rowNum, rowNum, 2, 3), sheet, workbook);
                        rowNum++;
                        // 获取整改前照片
                        String before = item.getPhotosBeforeRectification();
                        // 获取检查人员签字图片
                        XSSFDrawing drawing = sheet.createDrawingPatriarch();
                        int beforeNum = rowNum;
                        int afterNum = rowNum;
                        if (StringUtils.isNotEmpty(before)) {
                            List<String> list = JSONArray.parseArray(before, String.class);
                            String url = null;
                            if (null != list && list.size() > 0) {
                                for (String urlStr : list) {
                                    row = sheet.getRow(beforeNum);
                                    // 设置行高
                                    row.setHeightInPoints(300);
                                    url = urlStr.split("#")[0];
                                    drawingPicture(workbook, drawing, url, 1, 1, 1, 1, 0, beforeNum, 2, beforeNum + 1);
                                    beforeNum++;
                                }
                            }
                        }
                        // 获取整改后照片
                        String after = item.getPhotosAfterRectification();
                        if (StringUtils.isNotEmpty(after)) {
                            List<String> list = JSONArray.parseArray(after, String.class);
                            String url = null;
                            if (null != list && list.size() > 0) {
                                for (String urlStr : list) {
                                    row = sheet.getRow(afterNum);
                                    // 设置行高
                                    row.setHeightInPoints(300);
                                    url = urlStr.split("#")[0];
                                    drawingPicture(workbook, drawing, url, 1, 1, 1, 1, 2, afterNum, 4, afterNum + 1);
                                    afterNum++;
                                }
                            }
                        }
                        int num = beforeNum > afterNum ? beforeNum : afterNum;
                        rowNum = rowNum == num ? num + 1 : num;
                        index++;
                    }
                }
                row = sheet.getRow(rowNum);
                CellStyle style = workbook.createCellStyle();
                style.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
                // 设置字体
                XSSFFont font1 = workbook.createFont();
                font1.setFontName("宋体");
                font1.setFontHeightInPoints((short) 12);
                style.setFont(font1);
                row.createCell(0).setCellValue(report.getCorpName());
                row.getCell(0).setCellStyle(style);
                sheet.addMergedRegion(setRegion(rowNum, rowNum, 0, 3));
                rowNum++;
                row = sheet.getRow(rowNum);
                String reportTime = "";
                if (null != report.getReportTime()) {
                    reportTime = format.format(report.getReportTime());
                }
                row.createCell(0).setCellValue(reportTime);
                row.getCell(0).setCellStyle(style);
                sheet.addMergedRegion(setRegion(rowNum, rowNum, 0, 3));
            }
            return workbook;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            return null;
        }
    }

    @Override
    public void exportReportByPdf(String id, OutputStream os) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        try {
            // 获取整改报告数据
            MessageBean<HiddenDangerRectificationReport> msg = getReport(id);
            HiddenDangerRectificationReport report = null;
            if (msg.getCode() == BusinessCode.SUCCESS.getCode()) {
                if (null != msg.getData()) {
                    report = msg.getData();
                }
            }
            if (null == report) {
                return;
            }
            // 创建Document
            Document document = new Document();
            PdfWriter writer = PdfWriter.getInstance(document, os);
            writer.setViewerPreferences(PdfWriter.PageModeUseThumbs);
            // 设置页面大小
            document.setPageSize(PageSize.A4);
            document.open();
            // 设置字体
            // 标题
            Font headFont = getFont(14, Font.NORMAL);
            // 内容
            Font textFont = getFont(10, Font.NORMAL);
            PdfPCell cell = new PdfPCell();
            // 设置垂直对齐方式，默认居中
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            // 设置水平对齐方式
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setPhrase(new Paragraph(report.getReportName(), headFont));
            cell.setPadding(0);
            cell.setBorder(0);
            cell.setPaddingTop(0);
            cell.setPaddingBottom(10);
            cell.setColspan(2);
            // 创建一个PDF表单
            PdfPTable table = createTable(2);
            table.addCell(cell);
            table.addCell(createCell(report.getCheckUnitName(), textFont, Element.ALIGN_LEFT, 2, 0));
            StringBuffer sb = new StringBuffer();
            sb.append("根据隐患整改通知书").append(report.getNoticeCode()).append("整改要求，整改报告如下：");
            PdfPCell cell1 = new PdfPCell();
            // 设置垂直对齐方式，默认居中
            cell1.setVerticalAlignment(Element.ALIGN_MIDDLE);
            // 设置水平对齐方式
            cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell1.setColspan(2);
            Paragraph paragraph = new Paragraph(sb.toString(), textFont);
            paragraph.setIndentationLeft(20);
            cell1.addElement(paragraph);
            table.addCell(cell1);
            List<ReportItem> itemList = report.getReportItemList();
            if (null != itemList && itemList.size() > 0) {
                int index = 1;
                for (ReportItem item : itemList) {
                    table.addCell(createCell("问题" + index + "描述:" + item.getDescription(), textFont, Element.ALIGN_LEFT, 2, 0));
                    table.addCell(createCell("整改结果：" + item.getCorrectiveMeasures(), textFont, Element.ALIGN_LEFT, 2, 0));
                    table.addCell(createCell("计划时间：" + (null != item.getPlanTime() ? sdf.format(item.getPlanTime()) : ""), textFont, Element.ALIGN_LEFT, 0, 0));
                    table.addCell(createCell("完成整改时间：" + (null != item.getFinishTime() ? sdf.format(item.getFinishTime()) : ""), textFont, Element.ALIGN_LEFT, 0, 0));
                    table.addCell(createCell("整改前照片", textFont, Element.ALIGN_LEFT, 0, 0));
                    table.addCell(createCell("整改后照片", textFont, Element.ALIGN_LEFT, 0, 0));
                    // 获取整改前照片
                    String before = item.getPhotosBeforeRectification();
                    List<String> beforeList = new ArrayList<>();
                    if (StringUtils.isNotEmpty(before)) {
                        beforeList = JSONArray.parseArray(before, String.class);
                    }
                    // 获取整改后照片
                    String after = item.getPhotosAfterRectification();
                    List<String> afterList = new ArrayList<>();
                    if (StringUtils.isNotEmpty(after)) {
                        afterList = JSONArray.parseArray(after, String.class);
                    }
                    if (beforeList.size() > afterList.size()) {
                        int beforeNum = 0;
                        for (String url : afterList) {
                            // 设置整改前照片
                            Image beforeImage = Image.getInstance(beforeList.get(beforeNum).split("#")[0]);
                            //自定义大小
                            beforeImage.scaleAbsolute(300, 300);
                            table.addCell(new PdfPCell(beforeImage));
                            Image afterImage = Image.getInstance(url.split("#")[0]);
                            //自定义大小
                            afterImage.scaleAbsolute(300, 300);
                            table.addCell(new PdfPCell(afterImage));
                            beforeNum++;
                        }
                        while (beforeNum < beforeList.size()) {
                            // 设置剩下的整改前照片
                            Image beforeImage = Image.getInstance(beforeList.get(beforeNum).split("#")[0]);
                            //自定义大小
                            beforeImage.scaleAbsolute(300, 300);
                            table.addCell(new PdfPCell(beforeImage));
                            table.addCell(createCell("", textFont, Element.ALIGN_LEFT, 0, 0));
                            beforeNum++;
                        }
                    } else {
                        int afterNum = 0;
                        for (String url : beforeList) {
                            Image beforeImage = Image.getInstance(url.split("#")[0]);
                            //自定义大小
                            beforeImage.scaleAbsolute(300, 300);
                            table.addCell(new PdfPCell(beforeImage));
                            // 设置整改后照片
                            Image afterImage = Image.getInstance(afterList.get(afterNum).split("#")[0]);
                            //自定义大小
                            afterImage.scaleAbsolute(300, 300);
                            table.addCell(new PdfPCell(afterImage));
                            afterNum++;
                        }
                        while (afterNum < afterList.size()) {
                            table.addCell(createCell("", textFont, Element.ALIGN_LEFT, 0, 0));
                            // 设置剩下的整改后照片
                            Image afterImage = Image.getInstance(afterList.get(afterNum).split("#")[0]);
                            //自定义大小
                            afterImage.scaleAbsolute(300, 300);
                            table.addCell(new PdfPCell(afterImage));
                            afterNum++;
                        }
                    }
                }
            }
            table.addCell(createCell(report.getCorpName(), textFont, Element.ALIGN_RIGHT, 2, 0));
            table.addCell(createCell(sdf.format(report.getReportTime()), textFont, Element.ALIGN_RIGHT, 2, 0));
            document.add(table);
            document.close();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return;
        }

    }

    /**
     * 合并单元格
     *
     * @param firstRow
     * @param lastRow
     * @param firstCol
     * @param lastCol
     * @return
     */
    private CellRangeAddress setRegion(int firstRow, int lastRow, int firstCol, int lastCol) {
        // 合并单元格
        // 指定 4 个参数，起始行，结束行，起始列，结束列。然后这个区域将被合并
        CellRangeAddress region = new CellRangeAddress(firstRow, lastRow, firstCol, lastCol);
        return region;
    }

    /**
     * 合并单元格并画上边框线
     */
    private void mergedRegion(int border, CellRangeAddress cellRange, XSSFSheet sheet, XSSFWorkbook workbook) {
        sheet.addMergedRegion(cellRange);
        RegionUtil.setBorderTop(border, cellRange, sheet, workbook);
        RegionUtil.setBorderBottom(border, cellRange, sheet, workbook);
        RegionUtil.setBorderLeft(border, cellRange, sheet, workbook);
        RegionUtil.setBorderRight(border, cellRange, sheet, workbook);
    }

    public File getFile(String url) {
        //对本地文件命名
        String fileName = url.substring(url.lastIndexOf("."), url.length());
        File file = null;
        URL urlfile;
        InputStream inStream = null;
        OutputStream os = null;
        try {
            file = File.createTempFile("net_url", fileName);
            //下载
            urlfile = new URL(url);
            inStream = urlfile.openStream();
            os = new FileOutputStream(file);

            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = inStream.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        } finally {
            try {
                if (null != os) {
                    os.close();
                }
                if (null != inStream) {
                    inStream.close();
                }
            } catch (Exception e) {
                logger.error(e.getMessage(),e);
            }
        }
        return file;
    }

    /**
     * 纠正图片旋转
     *
     * @param srcImgPath
     */
    public void correctImg(String srcImgPath) {
        FileOutputStream fos = null;
        try {
            // 原始图片
            File srcFile = new File(srcImgPath);
            // 获取偏转角度
            int angle = getAngle(srcFile);
            if (angle != 90 && angle != 270) {
                return;
            }
            // 原始图片缓存
            BufferedImage srcImg = ImageIO.read(srcFile);
            // 宽高互换
            // 原始宽度
            int imgWidth = srcImg.getHeight();
            // 原始高度
            int imgHeight = srcImg.getWidth();
            // 中心点位置
            double centerWidth = ((double) imgWidth) / 2;
            double centerHeight = ((double) imgHeight) / 2;
            // 图片缓存
            BufferedImage targetImg = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);
            // 旋转对应角度
            Graphics2D g = targetImg.createGraphics();
            g.rotate(Math.toRadians(angle), centerWidth, centerHeight);
            g.drawImage(srcImg, (imgWidth - srcImg.getWidth()) / 2, (imgHeight - srcImg.getHeight()) / 2, null);
            g.rotate(Math.toRadians(-angle), centerWidth, centerHeight);
            g.dispose();
            // 输出图片
            fos = new FileOutputStream(srcFile);
            ImageIO.write(targetImg, "jpg", fos);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        } finally {
            if (fos != null) {
                try {
                    fos.flush();
                    fos.close();
                } catch (Exception e) {
                    logger.error(e.getMessage(),e);
                }
            }
        }
    }

    /**
     * 获取图片旋转角度
     *
     * @param file 上传图片
     * @return
     */
    private int getAngle(File file) {
        if (null == file) {
            return 0;
        }
        try {
            Metadata metadata = ImageMetadataReader.readMetadata(file);
            for (Directory directory : metadata.getDirectories()) {
                for (Tag tag : directory.getTags()) {
                    if ("Orientation".equals(tag.getTagName())) {
                        String orientation = tag.getDescription();
                        if (orientation.contains("90")) {
                            return 90;
                        } else if (orientation.contains("180")) {
                            return 180;
                        } else if (orientation.contains("270")) {
                            return 270;
                        }
                    }
                }
            }
            return 0;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return 0;
        }
    }


    /**
     * 创建pdf表格
     *
     * @param colNumber
     * @return
     */
    public static PdfPTable createTable(int colNumber) {
        PdfPTable table = new PdfPTable(colNumber);
        try {
            // 设置表格总宽度
            table.setTotalWidth(540);
            // 设置宽度100%使用
            table.setWidthPercentage(100);
            // 锁定设置的宽度
            table.setLockedWidth(true);
            // 默认居中
            table.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.getDefaultCell().setBorder(1);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return table;
    }

    /**
     * 获取字体
     *
     * @param size  字体大小
     * @param style 字体风格，普通、加粗等
     * @return
     */
    public static Font getFont(int size, int style) {
        Font font = null;
        try {
            BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            font = new Font(baseFont, size, style);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return font;
    }

    /**
     * 创建单元格
     *
     * @param value   单元格值
     * @param font    单元格字体
     * @param align   水平对齐方式，如居中，居左，居右
     * @param colspan 合并单元格数量,不需要合并则输入0
     * @param rowspan 合并单元格数量,不需要合并则输入0
     * @return
     */
    public static PdfPCell createCell(String value, Font font, int align, int colspan, int rowspan) {
        if (null == value) {
            value = " ";
        }
        PdfPCell cell = new PdfPCell();
        // 设置垂直对齐方式，默认居中
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        // 设置水平对齐方式
        cell.setHorizontalAlignment(align);
        // 横向合并列
        if (colspan != 0) {
            cell.setColspan(colspan);
        }
        // 纵向合并行
        if (rowspan != 0) {
            cell.setRowspan(rowspan);
        }
        cell.setPhrase(new Paragraph(value, font));
        return cell;
    }

}
